/*
 * Flexigrid for jQuery - v1.1
 * 
 * Copyright (c) 2008 Paulo P. Marinas (code.google.com/p/flexigrid/) Dual
 * licensed under the MIT or GPL Version 2 licenses. http://jquery.org/license
 * 
 */
(function($) {
	$.addNiceGrid = function(t, p) {
		p = $.extend({ // apply default properties
			height : 200, // default height
			width : 'auto', // auto width
			striped : true, // apply odd even stripes
			novstripe : false,
			minwidth : 30, // min width of columns
			minheight : 80, // min height of columns
			resizable : true, // allow table resizing
			url : false, // URL if using data from AJAX 
			method : 'POST', // data sending method
			dataType : 'json', // type of data for AJAX, either xml or json
			errormsg : 'Connection Error',
			usepager : false,
			nowrap : true,
			page : 1, // current page
			total : 1, // total pages
			useRp : true, // use the results per page select box
			rp : 10, // results per page
			rpOptions : [5, 10, 15, 20, 30, 50], // allowed per-page values
			title : false,
			pagestat : 'Displaying {from} to {to} of {total} items',
			pagetext : 'Page',
			outof : 'of',
			findtext : 'Find',
			procmsg : 'Processing, please wait ...',
			query : '',
			qtype : '',
			nomsg : 'No items',
			minColToggle : 1, // minimum allowed column to be hidden
			showToggleBtn : true, // show or hide column toggle popup
			hideOnSubmit : true,
			autoload : true,
			blockOpacity : 0.5,
			preProcess : false,
			onDragCol : false,
			onToggleCol : false,
			onChangeSort : false,
			onSuccess : false,
			onError : false,
			onSubmit : false, // using a custom populate function
			subGrid : false,
			columnResizable : true,
			columnSwitchable : false,
			style : null,
			singleSelect : true,
			data_id : "name", // json record unique identifer
			colDefaults : null, // default config for all columns
			hideHeaderRow : false, // hide the header of table
			selectable : true,
			frontPaging : true
				// use front-end paging

		}, p);

		// apply default column config
		if (p.colDefaults) {
			p.colModel.each(function() {
						$.extend(this, p.colDefaults);
					});
		}

		// init divs
		g.gDiv = document.createElement('div'); // create global container
		g.mDiv = document.createElement('div'); // create title container
		g.hDiv = document.createElement('div'); // create header container
		g.bDiv = document.createElement('div'); // create body container
		g.cDrag = document.createElement('div'); // create column drag
		g.nDiv = document.createElement('div'); // create column show/hide popup
		g.nBtn = document.createElement('div'); // create column show/hide
												// button
		g.pDiv = document.createElement('div'); // create pager container

		// row count
		var count = 0;

		// create grid class
		var g = {
			addData : function(data) { // parse data
				if (p.dataType == 'json') {
					data = $.extend({
								result : [],
								page : 0,
								total : 0
							}, data);
				}
				if (p.preProcess) {
					data = p.preProcess(data);
				}
				if (!p.usepager) {
					data.page = 1;
					data.total = 1;
				}
				$('.pReload', this.pDiv).removeClass('loading');
				this.loading = false;
				if (!data) {
					$('.pPageStat', this.pDiv).html(p.errormsg);
					return false;
				}
				if (p.frontPaging) {
					p.total = data.result.length;
				} else {
					p.total = data.total;
				}

				if (p.total == 0) {
					$('tr, a, td, div', t).unbind();
					$(t).empty();
					p.pages = 1;
					p.page = 1;
					this.buildpager();
					$('.pPageStat', this.pDiv).html(p.nomsg);
					return false;
				}
				p.pages = Math.ceil(p.total / p.rp);
				if (!p.frontPaging) {
					p.page = data.page;
				}
				this.buildpager();
				g.currPageData = data;
				if (p.frontPaging) {
					data = g.doPaging(data);
				}
				// build new body
				var tbody = document.createElement('tbody');

				$.each(data.result, function(i, row) {
					count = i;
					var tr = document.createElement('tr');
					if (i % 2 && p.striped) {
						tr.className = 'erow';
					}
					if (row[p.data_id]) {
						$(tr).attr({
									"id" : row[p.data_id] || $.fn.genId()
								});
					}
					if (p.checkbox) {
						var cth = $('<th/>');
						var cthch = $('<input type="checkbox" value="'
								+ row[p.data_id] + '"/>');
						var objTr = $(tr);
						cthch.addClass("noborder").click(function() {
									if (this.checked) {
										objTr.addClass('trSelected');
										if (p.singleSelect) { // singleSelect
											$("input:first", objTr.siblings())
													.attr({
																"checked" : false
															});
											objTr.siblings()
													.removeClass('trSelected');
										}

									} else {
										objTr.removeClass('trSelected');
									}
								});
						cth.addClass("cth").attr({
									"align" : "center",
									width : "40",
									height : "30"
								}).append(cthch);
						$(tr).prepend(cth);
					}
					// add sub grid icon by xp
					if (p.subGrid) {
						var sgth = $('<th/>');
						var icon = $('<div/>');
						var objTr = $(tr);
						var subId = $.fn.genId();
						icon.addClass("expand").click(function() {
							if (this.className == "collapse") {
								$(this).removeClass("collapse");
								$(this).addClass("expand");
								objTr.next().remove();
							} else {
								$(this).removeClass("expand");
								$(this).addClass("collapse");

								var colTotal = (function() {
									var t = 0;
									$.each(p.colModel, function() {
												t++;
											});
									return t;
								})();
								objTr
										.after($('<tr style="width:100%;" role="row"  class="subgrid">'
														+ '<td colSpan="1"/>'
														+ '<td colSpan='
														+ (colTotal)
														+ '>'
														+ '<table id='
														+ subId
														+ '></table>'
														+ '</td>'
														+ '</tr>'));

								g.addSubGrid($("#" + subId), p.subGrid, row);

							}
						});
						sgth.attr({
									width : "40",
									"align" : "center",
									height : "30px"
								}).addClass("sgth").append(icon);
						$(tr).prepend(sgth);
					}
					// add sub grid icon by xp end/
					$('thead tr:first th', g.hDiv).each( // add cell
							function() {
						var td = document.createElement('td');
						td.align = this.align;
						var idx = $(this).attr('axis').substr(3);
						var col = p.colModel[idx];
						var t = "";
						if (typeof row[idx] != "undefined" && row[idx] != null) {
							t = row[idx]; // null-check for Opera-browser
						} else {
							// enable mapping by xp
							if (col.mapping) {
								if (/^([^\.]+\.)+[^\.]+$/.test(col.mapping)) {
									try {
										eval("t = row." + col.mapping);
									} catch (_) {
									}
								}
								// enable mapping by xp end /
							} else {
								t = row[col.name];
							}
						}

						if (typeof col.renderer != "undefined") {
							t = col.renderer(t, row);
						}
						if (typeof col.plugins != "undefined") {
							t = "<div id='" + ("c" + row[p.data_id])
									+ "'  class='sparkchart'></div>";
						}
						if ((typeof t) == "string") {
							td.innerHTML = t;
						} else {
							$(td).append(t);
						}
						$(td).attr('abbr', $(this).attr('abbr'));
						$(tr).append(td);
						td = null;
					}

					);

					$(tbody).append(tr);
					tr = null;
				});

				$('tr', t).unbind();
				$(t).empty();
				$(t).append(tbody);
				this.addCellProp();
				this.addRowProp();
				this.rePosDrag();
				tbody = null;
				data = null;
				i = null;
				if (p.onSuccess) {
					p.onSuccess(this);
				}
				if (p.hideOnSubmit) {
					$(g.block).remove();
				}
				this.hDiv.scrollLeft = this.bDiv.scrollLeft;
				if ($.browser.opera) {
					$(t).css('visibility', 'visible');
				};

				count = count + 1;
				var size = (p.height == 'auto') ? 'auto' : p.height + "px";
				if (count < 8) {
					size = "300px";
				} else
					size = count * 35 + "px";

				// var aa = count + " - " + size;
				// alert(aa)
				this.reHeightBdiv(size);
			}
		};
	}
})(jQuery);